/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.postbar.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class MSiteLocation {
    
    static private final Logger logger = Logger.getLogger(MSiteLocation.class.getName());
    
    public long[] httpClientSend(String url, String requestString) {
        logger.info(url + " JettyClient POST send begin!");
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String rs = "";
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(url);
//            ByteArrayEntity entity = new ByteArrayEntity(requestString.getBytes());
            StringEntity entity = new StringEntity(requestString, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
//            entity.setChunked(true);
            httppost.setEntity(entity);
            response = httpClient.execute(httppost);
            logger.debug(url + " sending finished!");
            StatusLine st = response.getStatusLine();
            
            if (st.getStatusCode() == 200) {
                logger.debug(url + " JettyClient send getStatusCode is 200!");
                rs = HttpResponseParser.getResponseContent(response);
                logger.debug("the return message is " + rs);
                //{"count":0,"msg":"参数错误","qTime":0,"status":-1}
                JSONObject object = JSONObject.parseObject(rs);
                int status = (int) object.get("status");
                int count = (int) object.get("count");
                int qTime = (int) object.get("qTime");
                String msg = (String) object.get("msg");
                Long[] retData = new Long[count];
                if (status == 0) {
                    logger.info(url + "send yunrun succeed,and return count is " + count + " ,and qTime is " + qTime + " ,and the msg is " + msg + " ,and the data is " + object.getJSONArray("data").toJSONString());
                    JSONArray dataArray = object.getJSONArray("data");
                    retData = (Long[]) dataArray.toArray();
                    return ArrayUtils.toPrimitive(retData);
                } else {
                    logger.error(url + "send yunrun failed,and return count is " + count + " ,and qTime is " + qTime + " ,and the msg is " + msg);
                    return null;
                }
            } else {
                logger.error(url + " JettyClient send getStatusCode is not 200!");
                return null;
            }
        } catch (Exception ex) {
            logger.error(url + " JettyClient send error!" + ex.getMessage() + "|" + ex.getLocalizedMessage() + ex);
            return null;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
    }
    
    public int[] send(String url, Map<String, String> map) {
        logger.info(url + " JettyClient POST send begin!");
        String html = "";
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        CloseableHttpResponse response = null;
        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        if (map != null && map.size() > 0) {
            for (Map.Entry<String, String> e : map.entrySet()) {
                formparams.add(new BasicNameValuePair(e.getKey(), e.getValue()));
            }
        }
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "utf-8");
            httppost.setEntity(uefEntity);
            httppost.addHeader("User-Agent", "iie_bdtb");
            response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
                html = EntityUtils.toString(response.getEntity());
                JSONObject object = JSONObject.parseObject(html);
                int status = (int) object.get("status");
                int count = (int) object.get("count");
                int qTime = (int) object.get("qTime");
                String msg = (String) object.get("msg");
                if (status == 0) {
                    logger.info(url + " send yunrun succeed,and return count is " + count + " ,and qTime is " + qTime + " ,and the msg is " + msg);
//                    logger.info(url + " and the data is " + object.getJSONArray("data").toJSONString());
                    JSONArray dataArray = object.getJSONArray("data");
                    int[] array = new int[dataArray.size()];
                    logger.info(url + " send yunrun return " + dataArray.size() + " record.");
                    for (int i = 0; i < dataArray.size(); i++) {
                        array[i] = dataArray.getIntValue(i);
                    }
                    return array;
                } else {
                    logger.error(url + " send yunrun failed,and return count is " + count + " ,and qTime is " + qTime + " ,and the msg is " + msg);
                    return null;
                }
            } else {
                logger.error(url + " JettyClient send getStatusCode is not 200!");
                return null;
            }
        } catch (Exception ex) {
            logger.error(url + " JettyClient send error!" + ex.getMessage() + ex);
            return null;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
    }
}
